package com.shuqi.database.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

import android.content.Context;
import android.text.TextUtils;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.database.dao.OrmBaseDao;
import com.shuqi.database.model.UserInfo;

/**
 * 
 * @author yaozhen
 * 
 */
public class AccountDao extends OrmBaseDao {

    private static AccountDao mInstance;

    private RuntimeExceptionDao<UserInfo, String> mDao = AccountDatabaseHelper.getHelper(
            ShuqiApplication.getContext()).getRuntimeExceptionDao(UserInfo.class);

    private AccountDao(Context context) {

    }

    public static synchronized AccountDao getInstance() {
        if (mInstance == null) {
            mInstance = new AccountDao(ShuqiApplication.getContext());
        }
        return mInstance;
    }

    /**
     * 补全字段
     * 
     * @return
     */
    private UserInfo fillInfo(UserInfo info, UserInfo dbInfo) {
        if (info == null) {
            return null;
        }
        if (dbInfo == null) {
            return info;
        }
        if (!TextUtils.isEmpty(info.getEmail())) {
            dbInfo.setEmail(info.getEmail());
        }
        if (!TextUtils.isEmpty(info.getGender())) {
            dbInfo.setGender(info.getGender());
        }
        if (!TextUtils.isEmpty(info.getMobile())) {
            dbInfo.setMobile(info.getMobile());
        }
        if (!TextUtils.isEmpty(info.getNickName())) {
            dbInfo.setNickName(info.getNickName());
        }
        if (!TextUtils.isEmpty(info.getSession())) {
            dbInfo.setSession(info.getSession());
        }
        if (!TextUtils.isEmpty(info.getSinaKey())) {
            dbInfo.setSinaKey(info.getSinaKey());
        }
        if (!TextUtils.isEmpty(info.getSinaName())) {
            dbInfo.setSinaName(info.getSinaName());
        }
        if (!TextUtils.isEmpty(info.getBalance())) {
            dbInfo.setBalance(info.getBalance());
        }
        if (info.getUserState() > UserInfo.INT_DEFAULT) {
            dbInfo.setUserState(info.getUserState());
        }
        if (info.getLoginState() > UserInfo.INT_DEFAULT) {
            dbInfo.setLoginState(info.getLoginState());
        }
        if (info.getLoginTime() > UserInfo.INT_DEFAULT) {
            dbInfo.setLoginTime(info.getLoginTime());
        }

        return dbInfo;
    }

    /** 创建或者更新表中的UserInfo 如果字段为空，会忽略更新该字段 */
    public int saveUserInfo(final UserInfo info) {
        if (info == null || TextUtils.isEmpty(info.getUserId())) {
            return -1;
        }
        try {
            List<UserInfo> oldInfoList = mDao.queryForEq("user_id", info.getUserId());
            UserInfo oldInfo = null;
            if (oldInfoList != null && oldInfoList.size() > 0) {
                oldInfo = oldInfoList.get(0);
            }
            UserInfo dbInfo = fillInfo(info, oldInfo);
            mDao.createOrUpdate(dbInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 1;
    }

    /** 获取当前登录账户的信息 */
    public UserInfo getLoginAccount() {
        QueryBuilder<UserInfo, String> queryBuilder = mDao.queryBuilder();

        try {
            queryBuilder.where().eq("login_state", UserInfo.LOGINSTATE_LOGINED);
            List<UserInfo> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    /** 获取全部用户 */
    public List<UserInfo> getAllAccounts() {
        QueryBuilder<UserInfo, String> queryBuilder = mDao.queryBuilder();
        queryBuilder.orderBy("login_time", false);
        List<UserInfo> list = null;
        try {
            list = queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 更新用户的验证状态
     * 
     * @param uid 用户uid
     * @param uerstate 用户的验证状态
     * @return
     */
    public int updateUserInfoUserState(String uid, int uerstate) {
        if (TextUtils.isEmpty(uid)) {
            return -1;
        }

        UpdateBuilder<UserInfo, String> updateBuilder = mDao.updateBuilder();
        try {
            updateBuilder.updateColumnValue("user_state", uerstate);
            updateBuilder.where().eq("user_id", uid);
            return updateBuilder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 更新用户的新浪微博绑定信息
     * 
     * @param uid
     * @param sinaKey
     * @param sinaName
     * @return
     */
    public int updateUsetSinaInfo(String uid, String sinaKey, String sinaName, String sessinon) {
        if (TextUtils.isEmpty(uid)) {
            return -1;
        }

        UpdateBuilder<UserInfo, String> updateBuilder = mDao.updateBuilder();
        try {
            updateBuilder.updateColumnValue("sina_key", sinaKey);
            updateBuilder.updateColumnValue("sina_name", sinaName);
            if (!TextUtils.isEmpty(sessinon)) {
                updateBuilder.updateColumnValue("session", sessinon);
            }
            updateBuilder.where().eq("user_id", uid);
            return updateBuilder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return -1;
    }


    /**
     * 存储登录的用户信息
     * 
     * @param info
     */
    public void saveLoginUserInfo(final UserInfo info) {
        if (info == null || TextUtils.isEmpty(info.getUserId())) {
            return;
        }
        try {
            Callable<Void> callble = new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    UpdateBuilder<UserInfo, String> updateBuilder = mDao.updateBuilder();
                    updateBuilder.updateColumnValue("login_state", UserInfo.LOGINSTATE_UNLOGIN);
                    updateBuilder.update();
                    // 保持当前用户登录时间，根据用户登录时间排序用
                    info.setLoginTime(System.currentTimeMillis());
                    mDao.createOrUpdate(info);
                    return null;
                }
            };

            openTransactionManager(AccountDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据uid删除用户信息
     * 
     * @param uid
     */
    public int delteUserInfoByUid(final String uid) {
        if (TextUtils.isEmpty(uid)) {
            return -1;
        }
        DeleteBuilder<UserInfo, String> delBuilder = mDao.deleteBuilder();
        try {
            delBuilder.where().eq("user_id", uid);
            return delBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 修改用户资料
     * 
     * @param uid
     * @param gender
     * @param nickName
     */
    public void modfyUserInfo(String uid, int gender, String nickName) {
        if (TextUtils.isEmpty(uid)) {
            return;
        }
        try {
            UpdateBuilder<UserInfo, String> updateBuilder = mDao.updateBuilder();
            updateBuilder.updateColumnValue("gender", gender);
            updateBuilder.updateColumnValue("nike_name", nickName);
            updateBuilder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
